package com.wiener.core.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.wiener.core.domain.Role;
import com.wiener.core.domain.Usuario;

@Repository
public class UsuarioDAOImpl extends HibernateDaoSupport implements UsuarioDAO {

	@Autowired
	public UsuarioDAOImpl(SessionFactory sessionFactory) {
		setSessionFactory(sessionFactory);
	}

	@Override
	public Usuario findUserByUserName(String usuario) throws Exception{
		// TODO Auto-generated method stub
		Object[] params = new Object[1];
		params[0] = usuario; 
		
		List<Usuario> list = (List<Usuario>)getHibernateTemplate().find( "from Usuario where usuario = ?", params);
		if (list != null && list.size() > 0) return list.get(0); 
		
		return null;
	}

	@Override
	public List<Role> findSecurityRoleByUserName(String usuario) throws Exception {
		// TODO Auto-generated method stub
		StringBuffer query = new StringBuffer(" ");
		query.append(" select r ");
		query.append(" from Usuario u ,	UsuariosRoles ur, Role r");
		query.append(" where u.usuario = ? and u.id = ur.usuarioid and ur.roleid = r.id "); 
		query.append(" )");
		Object[] params = new Object[1];
		logger.info("userName = " + usuario);
		params[0] = usuario;		
		return getHibernateTemplate().find(query.toString(),params);
	}
}
